// const nums = [-7, -3, 2, 3, 11]
const nums = [-4,-1,0,3,10];
// 输出：[4,9,9,49,121]

// 暴力解法
var sortedSquares1 = function (nums) {
  const newArr = nums.map(e => Math.pow(e, 2));
  return newArr.sort((a, b) => a - b);
};

// 双指针解法
var sortedSquares = function (nums) {
  let left = 0;
  let right = nums.length - 1;
  let k = nums.length - 1;
  let res = new Array(nums.length);
  while (left <= right) {
    const lfS = nums[left] * nums[left];// 左边的平方
    const rgS = nums[right] * nums[right];// 右边的平方
    // debugger
    if (lfS < rgS) {
      // k在最右边 取了右边值 right指针往左走
      res[k] = rgS;
      right--;
    } else {
      // 取了左边值 left往右边走
      res[k] = lfS;
      left++;
    }
    k--;
  }
  return res;
};


console.log(sortedSquares(nums));